package two_shang._12_03;
//如类名所示：向文件中写入对象

import java.io.*;

public class WriteObjectToFile {
    public static void main(String[] args) {
        Product iphone = new Product(1, "iPhone", new String[]{"Electronics", "Mobile"}, 999.99);
        Product ipad = new Product(2, "iPad", new String[]{"Electronics", "Tablet"}, 799.99);
        Product macbook = new Product(3, "MacBook", new String[]{"Electronics", "Laptop"}, 1299.99);
        Product iwatch = new Product(4, "Apple Watch", new String[]{"Electronics", "Wearable"}, 399.99);

        // 写入对象
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("X:\\IntelliJ IDEA 2023.1.2\\project\\ClassTest\\src\\two_shang._12_03\\File\\products.dat"))) {
            oos.writeObject(iphone);
            oos.writeObject(ipad);
            oos.writeObject(macbook);
            oos.writeObject(iwatch);
            System.out.println("对象写入成功");
        } catch (IOException e) {
            System.out.println("写入对象时出现错误：" + e.getMessage());
        }

        // 读取对象
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("X:\\IntelliJ IDEA 2023.1.2\\project\\ClassTest\\src\\two_shang._12_03\\File\\products.dat"))) {
            Product product1 = (Product) ois.readObject();
            Product product2 = (Product) ois.readObject();
            Product product3 = (Product) ois.readObject();
            Product product4 = (Product) ois.readObject();

            System.out.println("从文件中读取的对象：");
            System.out.println(product1.getId() + " - " + product1.getName());
            System.out.println(product2.getId() + " - " + product2.getName());
            System.out.println(product3.getId() + " - " + product3.getName());
            System.out.println(product4.getId() + " - " + product4.getName());
        } catch (IOException | ClassNotFoundException e) {
            System.out.println("读取对象时出现错误：" + e.getMessage());
        }
    }
}


class Product implements Serializable {
    private int id;
    private String name;
    private String[] categories;
    private double price;

    public Product(int id, String name, String[] categories, double price) {
        this.id = id;
        this.name = name;
        this.categories = categories;
        this.price = price;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String[] getCategories() {
        return categories;
    }

    public double getPrice() {
        return price;
    }
}
